package server;

import java.io.StringReader;
import java.net.Socket;
import java.util.Locale;
import java.util.Scanner;

public class ServerThread extends Thread
{
    private Socket socket = null;
    private int upperBound;
    private int bottomBound;
    float epsilon;

    public ServerThread(Socket socket, float epsilon)
    {
        this.epsilon = epsilon;
        this.socket = socket;
    }

    public void setBounds(int upperBound, int bottomBound)
    {
        this.upperBound = upperBound;
        this.bottomBound = bottomBound;
    }

    public void run()
    {
        try
        {
            TaskProtocol taskProtocol = new TaskProtocol(socket);
            boolean isConverged = false;
            while (!isConverged)
            {
                float [][] taskData = Server.getTaskData(upperBound, bottomBound);
                int rowsCount = taskData.length;
                int columnsCount = taskData[0].length;
                String requestString = epsilon + "\n";
                requestString += this.matrixToString(taskData);
                taskProtocol.writeString(requestString);
                String clientResponse = taskProtocol.readString();
                System.out.println("Got response from client:\n" + clientResponse);

                Scanner inputScanner = new Scanner(new StringReader(clientResponse));
                inputScanner.useLocale(Locale.ENGLISH);
                float [][] countedMatrix = matrixFromString(inputScanner, rowsCount, columnsCount);
                Server.updateGrid(countedMatrix, upperBound, bottomBound);
                isConverged = (inputScanner.nextFloat() != 0);
            }
            socket.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    private float[][] matrixFromString(Scanner inputScanner, int rowsCount, int columnsCount)
    {
        float [][] matrix = new float[rowsCount][columnsCount];
        for (int i = 0; i < rowsCount; i++)
        {
            for (int j = 0; j < columnsCount; j++)
            {
                matrix[i][j] = inputScanner.nextFloat();
            }
        }
        return matrix;
    }

    public static String matrixToString(float[][] matrix)
    {
        int rowsCount = matrix.length;
        int columnsCount = matrix[0].length;
        String matrixString = rowsCount + " " + columnsCount + "\n";
        for (int i = 0; i < rowsCount; i++)
        {
            for (int j = 0; j < columnsCount; j++)
            {
                matrixString += matrix[i][j];
                if (j != columnsCount - 1)
                {
                    matrixString += ' ';
                }
            }
            matrixString += '\n';
        }
        return matrixString;
    }

}